import React from 'react';
import {ScrollView,Button,Alert, StyleSheet, Text,TouchableOpacity, View, FlatList,Image} from 'react-native';
import FontAwesome5Icon from 'react-native-vector-icons/FontAwesome5';
import Dialog, {
  DialogTitle,
  DialogContent,
  DialogButton,
  ScaleAnimation,
} from 'react-native-popup-dialog'
import pic1 from '../pic/树1末.png'
import pic2 from '../pic/树2末.png'
import pic3 from '../pic/树3末.png'
import pic4 from '../pic/树4末.png'
import pic5 from '../pic/树5末.png'
import pic6 from '../pic/树6末.png'

export default class Shop extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            ScaleAnimationDialog:false,            
            data:[],
            resdata:[],
            money:0,
            current_info:{}
          }
        this.onPress1 = this.onPress1.bind(this);
        this.onPress2 = this.onPress2.bind(this);
        this.Item = this.Item.bind(this);
        this.if_purchase= this.if_purchase.bind(this);
        this.setScaleAnimationDialog = this.setScaleAnimationDialog.bind(this);
        this.Dialog_new = this.Dialog_new.bind(this);
        this.setcurrentinfo = this.setcurrentinfo.bind(this);
    }
    componentDidMount() {
        var data=[
          {
          name: 'Tree1' ,
          id:1,
          img_url: pic1,
          price : 15,
          if_had : 0,
          reward : 25,
          mins : 30
          }, 
          {
            name: 'Tree2' ,
            id:2,
            img_url: pic2,
            price : 15,
            if_had : 0,
            reward : 25,
            mins : 30
          }, 
          {
              name: 'Tree3' ,
              id:3,
              img_url: pic3,
              price : 15 ,
              if_had : 0,
              reward : 25,
              mins : 30
          },
          {
              name: 'Tree4' ,
              id:4,
              img_url: pic4,
              price : 15 ,
              if_had : 0,
              reward : 25,
              mins : 30
          },
          {
            name: 'Tree5' ,
            id:5,
            img_url: pic5,
            price : 150,
            if_had : 0,
            reward : 100,
            mins : 30
          },
          {
            name: 'Tree6' ,
            id:6,
            img_url: pic6,
            price : 1000 ,
            if_had : 0,
            reward : 500,
            mins : 30
          },        
        ];
        fetch("http://192.168.1.106:3000/trees")
        .then((response) => response.json())
        .then((responseData) => {
            console.log(responseData)
            var temp = []
            data.forEach((element,index)=>{
              element.if_had = responseData['trees'][index].if_had
              temp.push(element)
            })
            this.setState({
              data: temp,
              money:responseData['icon'],
              current_info: temp[5],
              resdata:responseData['trees']
            })
            // set(responseData)
        })
        .catch((error) => {
            console.error(error)
        })
    }
    setScaleAnimationDialog(visible){
      this.setState({ScaleAnimationDialog:visible})
      this.forceUpdate();
    }

    setcurrentinfo({item}){
      this.setState({current_info:item})
    };

    onPress1 = ({name}) => {
        Alert.alert('Caution','Purchase Confirmation',[
            {text:'Confirmation',onPress:()=>{this.onPress2({name})}},
            {text:'Cancel',style:'cancel'}
            ],{cancelable:false})     
    }

    onPress2 = ({name}) => {
      let m = 0;
      let t_m = this.state.money;
      this.state.data.forEach((item,index,array)=>{
        if(item.name == name)
        {   
            if(t_m >= item.price){
              item.if_had = 1,
              // console.log(this.state.resdata)
              this.state.resdata[index].if_had = 1
              t_m -= item.price;
              fetch('http://192.168.1.106:3000/trees/',{
                method:'put',
                body:JSON.stringify({icon:t_m,trees:this.state.resdata}),
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(response=>{ return response.text()})
            .then(ret=>{
            //相关逻辑
            }) 
              this.state.money=t_m;
              this.forceUpdate()
              // console.log(this.state.data);      
            }
            else{
              Alert.alert("You don't have enough coins")
            }               
        }                               
      })
    }

    if_purchase({item}){
      const name = item.name;
      if(item.if_had == 0){
        return(
          <TouchableOpacity style={{height:50,width:58, justifyContent:"center",alignItems:"center",paddingTop:25}} onPress = {() => {this.onPress1({name})}} >
            <Text style={{color:"green"}}>Buy</Text>
          </TouchableOpacity>
        )
      }
      else{
        return(
          <Text style={{height:50,width:50, justifyContent:"center",alignItems:"center",paddingTop:27}}>owned</Text>
        )
      }
    }


    Item({item}){
        return (
            <View style={styles.listItem}>
                <TouchableOpacity onPress={() => {this.setScaleAnimationDialog(true);this.setcurrentinfo({item})}}>
                <Image source={item.img_url}  style={{width:60, height:60,borderRadius:30}} />
                </TouchableOpacity>
                
                <View style={{alignItems:"center",flex:1,padding:0}}>
                    <Text style={{fontWeight:"bold"}}>Type：{item.name}</Text>
                    <Text>Price：{item.price}</Text>
                    <Text>Reward：{item.reward}</Text>
                    <Text>Length：{item.mins}mins</Text>
                </View>
                <this.if_purchase item={item}/>
            </View>
        );
    } 
    
    Dialog_new(){
        return (
          <Dialog
          onTouchOutside={() => {
            this.setScaleAnimationDialog(false);
          }}
          width={0.9}
          visible={this.state.ScaleAnimationDialog}
          dialogAnimation={new ScaleAnimation()}
          onHardwareBackPress={() => {
            this.setScaleAnimationDialog(false);
            return true;
          }}
          dialogTitle={
            <DialogTitle
              title="Information"
              hasTitleBar={false}
            />
          }
          actions={[
            <DialogButton
              text="DISMISS"
              onPress={() => {
                this.setScaleAnimationDialog(false);
              }}
              key="button-1"
            />,
          ]}>
          <DialogContent>
            <View>
              <Text style = {{fontSize:15, fontFamily:'sans-serif'}}>
                Type: {this.state.current_info.name} {"\n"}
              </Text>
              
              <Button
                title="Close"
                onPress={() => {
                  this.setScaleAnimationDialog(false);
                }}
                key="button-1"
              />
            </View>
          </DialogContent>
        </Dialog>
        );
    }

  render(){
    return (
      <View style={styles.container}>
        <Text style={{fontWeight:"bold",paddingLeft:40,fontSize:21}}> <FontAwesome5Icon name={'coins'} size={18} color={'gold'}/> My Coins：{this.state.money}</Text>
        <FlatList
        data = {this.state.data}
        renderItem = {({item}) => <this.Item item={item}/>}
        // keyExtractor = {item => item}
        />
        <this.Dialog_new/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F7F7F7',
    marginTop:19
  },
  listItem:{
    margin:10,
    padding:10,
    backgroundColor:"#FFF",
    width:"80%",
    flex:1,
    alignSelf:"center",
    flexDirection:"row",
    borderRadius:5
  }
});
